package cn.itsource.org.controller;

import cn.hutool.core.util.RandomUtil;
import cn.itsource.basic.domain.AjaxResult;
import cn.itsource.basic.domain.WechartProperties;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.BinderDTO;
import cn.itsource.org.service.WechartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/wechart")
@Slf4j
public class WechartController {

    @Autowired
    private WechartProperties wechartProperties;
    @Autowired
    private WechartService wechartService;
    @Autowired
    private RedisService redisService;

    //申请微信登录
    @GetMapping("/apply")
    public String apply(){
        //https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect
        //生成一个唯一标识作为state
        //String state = UUID.randomUUID().toString().replace("-","");
        //生成完整的授权码URL
        String authorizationCodeUrl = String.format(wechartProperties.getAuthorizationCodeUrl(), wechartProperties.getAppId(), wechartProperties.getRedirectUri());
        return "redirect:"+authorizationCodeUrl;
    }
    //这里使我们的回调接口,用户一扫码登录,就会触发这个接口完成回调操作
    @GetMapping("/callback")
    public String callback(String code){
        log.info("进入回调接口,当前用户的code是:{}",code);

        return wechartService.callback(code);
    }

    @PostMapping("binder")
    @ResponseBody
    public AjaxResult binder (@RequestBody BinderDTO binderDTO){
        return wechartService.binder(binderDTO);
    }
    @GetMapping("sendmobilecode/{phone}")
    @ResponseBody
    public AjaxResult phoneFile(@PathVariable String phone){
        if(wechartService.exist(phone).getSuccess()){
            if(redisService.getKeyObjectValue("cpc", String.class) == null) {
                String code = RandomUtil.randomString(4);
                System.out.println("--------------验证码是:"+code+"--------------------");
                redisService.setStringKeyAndValue(phone, code, 5);
                redisService.setStringKeyAndValue("cpc", 0, 1);
                return AjaxResult.me();
            }else{
                return AjaxResult.setMsg("一分钟以内不能连续发送多次");
            }
        }
        return AjaxResult.setMsg("手机号异常");
    }




}